//使用方式

import { useSyncExternalStore } from 'react'

/***
 * import { useStorage } from './useStorage';
 * const [count, setCount] = useStorage('key', value);
 */
export const useStorage = (key: string, initialValue: any) => {
  const subscribe = (callback: () => void) => {
    window.addEventListener('storage', callback)
    return () => {
      window.removeEventListener('storage', callback)
    }
  }
  const getSnapshot = () => {
    return localStorage.getItem(key)
      ? JSON.parse(localStorage.getItem(key)!)
      : initialValue
  }
  const res = useSyncExternalStore(subscribe, getSnapshot)
  const updateStorage = (value: any) => {
    localStorage.setItem(key, JSON.stringify(value))
    //手动触发订阅
    window.dispatchEvent(new StorageEvent('storage'))
  }
  return [res, updateStorage]
}
